package com.happyrecyclingstation.interceptor;

import com.happyrecyclingstation.constant.JwtConstant;
import com.happyrecyclingstation.entity.User;
import com.happyrecyclingstation.properties.JwtProperties;
import com.happyrecyclingstation.service.UserService;
import com.happyrecyclingstation.utils.CurrentHolder;
import com.happyrecyclingstation.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 求职者令牌拦截器
 */
@Slf4j
@Component
public class JobSeekerTokenInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtProperties  jwtProperties;

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("进入求职令牌拦截器");
        //获取token
        String token = request.getHeader(jwtProperties.getJobSeekerToken());

        //判断token是否为空
        if (token == null || token.isEmpty()) {
            log.info("令牌为空，返回401");
            response.setStatus(401);
            return false;
        }

        //解析token令牌
        try {
            Claims claims = JwtUtils.parseToken(jwtProperties.getJobSeekerSecretKey(), token);
            User user = userService.getUserById((Integer) claims.get(JwtConstant.JOB_SEEKER_ID));
            if (user == null || user.getStatus() != 1) {
                log.info("用户已禁用，返回403");
                response.setStatus(403);
                return false;
            }

            //将用户id保存到当前线程中
            CurrentHolder.setCurrentId((Integer) claims.get(JwtConstant.JOB_SEEKER_ID));
        } catch (Exception e) {
            log.info("令牌非法，返回401");
            response.setStatus(401);
            return false;
        }

        //令牌正常放行
        log.info("令牌正常，放行");
        return true;
    }
}
